<?php
class Bzip2Package extends AbsPackage {
	protected $ext = '.bz2';
	/**
	 * when in length is too short, the compressed string is larger than original string
	 */
	public function compress($in = '') {
		$ret = '';
		if(is_string($in) && '' !== $in) {
			$ret = bzcompress($in);
		}
		
		return $ret;
	}
	
	public function uncompress($in = '') {
		$ret = '';
		if(is_string($in) && '' !== $in) {
			$ret = bzdecompress($in, true);
		}
		
		return $ret;
	}
	
	/**
	 * compress file to file
	 *
	 * @param string $in
	 * @param string $out
	 * @return mixed : null, true, false
	 */
	public function fcompress($in = null, $out = './') {
		$ret = null;
		if(null !== $in && is_file($in) && (is_file($out) || is_dir($out))) {
			$out = $this->formatCompressOut($in, $out);
			# 'OR' priority is less than '||', and less than '=', but '||' larger than '='
			$bz = @bzopen($out, 'w') OR FException::throwEx('bzopen fail');
			$content = @file_get_contents($in);
			@bzwrite($bz, $content, strlen($content)) OR FException::throwEx('write fail');
			$ret = @bzclose($bz);
		}
		
		return $ret;
	}
	
	public function funcompress($in = null, $out = './') {
		$ret = null;
		if(null !== $in && is_file($in) && (is_file($out) || is_dir($out))) {
			$out = $this->formatCompressOut($in, $out, false);
			# 'OR' priority is less than '||', and less than '=', but '||' larger than '='
			$bz = @bzopen($in, 'r') OR FException::throwEx('bzopen fail');
			while (!feof($bz)) {
				$content = @bzread($bz, 4096);
				if(false === $content) FException::throwEx('read fail');
				@file_put_contents($out, $content, FILE_APPEND);
			}
			$ret = @bzclose($bz);
		}
		
		return $ret;
	}
}
?>